<template>
  <div class="pdf-preview-container">
    <div class="pdf-preview-header">
      <div class="header-left">
        <h2>PDF 预览</h2>
        <!-- 内容长度提示 -->
        <div v-if="checkContentLength().isOverLimit" class="content-warning">
          <el-alert
            title="内容提示"
            type="warning"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>简历内容较多，可能影响PDF显示效果。建议精简内容或调整布局。</p>
            </template>
          </el-alert>
        </div>
      </div>
      <div class="pdf-actions">
        <el-button @click="downloadPDF" type="primary">下载 PDF</el-button>
        <el-button @click="printPDF">打印</el-button>
      </div>
    </div>
    
    <div class="pdf-pages" ref="pdfPagesRef">
      <!-- 单页PDF预览 -->
      <div 
        class="pdf-page"
        :style="getPageStyle()"
      >
        <div class="page-content" v-html="generateSinglePageContent()"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useResumeStore } from '@/store/resumeStore';
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
// 引入外部样式文件
import '@/assets/style/resume/pdf.css';

const resumeStore = useResumeStore();
const pdfPagesRef = ref(null);

// PDF页面样式
const getPageStyle = () => ({
  width: '210mm',
  height: '297mm',
  backgroundColor: '#ffffff',
  margin: '0 auto 20px auto',
  boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
  position: 'relative',
  pageBreakAfter: 'always'
});

// 计算PDF页面内容
const calculatePDFPages = () => {
  const pages = [];
  const pageHeight = 297; // A4高度（mm）
  const pageWidth = 210; // A4宽度（mm）
  const margin = 20; // 页边距（mm）
  const contentHeight = pageHeight - margin * 2;
  
  // 获取简历内容
  const resumeContent = generateResumeContent();
  
  // 将所有内容合并为一个连续的HTML字符串
  let allContent = '';
  let currentPageHeight = 0;
  let currentPageContent = '';
  
  // 基本信息模块
  if (resumeContent.basic.name || resumeContent.basic.phone || resumeContent.basic.email) {
    const basicHTML = generateBasicHTML();
    const basicHeight = calculateHTMLHeight(basicHTML);
    
    if (currentPageHeight + basicHeight > contentHeight) {
      // 需要换页
      pages.push({ content: currentPageContent });
      currentPageContent = basicHTML;
      currentPageHeight = basicHeight;
    } else {
      currentPageContent += basicHTML;
      currentPageHeight += basicHeight;
    }
  }
  
  // 教育经历模块
  const educationItems = resumeContent.education.filter(item => item.school || item.major);
  if (educationItems.length > 0) {
    const educationHTML = generateEducationHTML();
    const educationHeight = calculateHTMLHeight(educationHTML);
    
    if (currentPageHeight + educationHeight > contentHeight) {
      pages.push({ content: currentPageContent });
      currentPageContent = educationHTML;
      currentPageHeight = educationHeight;
    } else {
      currentPageContent += educationHTML;
      currentPageHeight += educationHeight;
    }
  }
  
  // 工作经验模块
  const workItems = resumeContent.work.filter(item => item.company || item.position);
  if (workItems.length > 0) {
    const workHTML = generateWorkHTML();
    const workHeight = calculateHTMLHeight(workHTML);
    
    if (currentPageHeight + workHeight > contentHeight) {
      pages.push({ content: currentPageContent });
      currentPageContent = workHTML;
      currentPageHeight = workHeight;
    } else {
      currentPageContent += workHTML;
      currentPageHeight += workHeight;
    }
  }
  
  // 技能特长模块
  if (resumeContent.skills.length > 0) {
    const skillsHTML = generateSkillsHTML();
    const skillsHeight = calculateHTMLHeight(skillsHTML);
    
    if (currentPageHeight + skillsHeight > contentHeight) {
      pages.push({ content: currentPageContent });
      currentPageContent = skillsHTML;
      currentPageHeight = skillsHeight;
    } else {
      currentPageContent += skillsHTML;
      currentPageHeight += skillsHeight;
    }
  }
  
  // 添加最后一页
  if (currentPageContent.trim()) {
    pages.push({ content: currentPageContent });
  }
  
  // 如果没有内容，至少显示一页
  if (pages.length === 0) {
    pages.push({ content: generateEmptyPageHTML() });
  }
  
  pdfPages.value = pages;
  console.log('PDF页面计算完成，共', pages.length, '页');
};

// 计算HTML内容的高度（简化版本）
const calculateHTMLHeight = (html) => {
  // 基于HTML内容估算高度
  const lines = html.split('<br>').length + html.split('</div>').length;
  const estimatedHeight = lines * 8 + 50; // 每行8mm + 基础高度50mm
  return Math.min(estimatedHeight, 200); // 最大200mm
};

// 生成简历内容
const generateResumeContent = () => {
  return {
    basic: {
      name: resumeStore.form.name || '未填写姓名',
      phone: resumeStore.form.phone || '未填写电话',
      email: resumeStore.form.email || '未填写邮箱',
      intention: resumeStore.form.intention || '未填写求职意向',
      intro: resumeStore.form.intro || '未填写个人简介',
      photoUrl: resumeStore.form.photoUrl
    },
    education: resumeStore.educationList,
    work: resumeStore.workList,
    skills: resumeStore.skillsList
  };
};

// 生成页面HTML
const generatePageHTML = (content) => {
  const template = resumeStore.currentTemplate;
  const style = template?.style || {};
  
  return `
    <div style="
      font-family: ${style.base?.fontFamily || 'Microsoft YaHei, sans-serif'};
      color: ${style.base?.primaryColor || '#333'};
      padding: 20px;
      height: 100%;
      box-sizing: border-box;
    ">
      ${content}
    </div>
  `;
};

// 生成基本信息HTML
const generateBasicHTML = () => {
  const basic = generateResumeContent().basic;
  const template = resumeStore.currentTemplate;
  const style = template?.style || {};
  
  return `
    <div style="margin-bottom: 20px;">
      <h1 style="
        font-size: ${style.basic?.name?.fontSize || 24}px;
        font-weight: ${style.basic?.name?.fontWeight || 'bold'};
        color: ${style.basic?.name?.color || style.base?.primaryColor || '#333'};
        margin: 0 0 10px 0;
        text-align: ${style.basic?.name?.textAlign || 'left'};
      ">${basic.name}</h1>
      
      <div style="margin-bottom: 10px;">
        <span style="margin-right: 20px;">电话：${basic.phone}</span>
        <span style="margin-right: 20px;">邮箱：${basic.email}</span>
        <span>意向：${basic.intention}</span>
      </div>
      
      ${basic.intro ? `
        <p style="
          font-size: ${style.basic?.intro?.fontSize || 14}px;
          line-height: ${style.basic?.intro?.lineHeight || 1.6};
          color: ${style.basic?.intro?.color || style.base?.secondaryColor || '#666'};
          margin: 10px 0;
          padding: 10px;
          background-color: ${style.basic?.intro?.backgroundColor || '#f8f9fa'};
          border-radius: ${style.basic?.intro?.borderRadius || 4}px;
        ">${basic.intro}</p>
      ` : ''}
    </div>
  `;
};

// 生成教育经历HTML (限制3个)
const generateEducationHTML = (limitedEducation = null) => {
  const education = limitedEducation || generateResumeContent().education.slice(0, 3);
  const template = resumeStore.currentTemplate;
  const style = template?.style || {};
  
  if (!education.length || education.every(item => !item.school && !item.major)) {
    return '';
  }
  
  let html = `
    <div style="margin-bottom: 15px;">
      <h2 style="
        font-size: ${style.education?.title?.fontSize || 16}px;
        font-weight: ${style.education?.title?.fontWeight || 'bold'};
        color: ${style.education?.title?.color || style.base?.primaryColor || '#333'};
        margin: 0 0 10px 0;
        padding-bottom: 3px;
        border-bottom: 2px solid ${style.education?.title?.borderBottom || style.base?.primaryColor || '#333'};
      ">教育经历</h2>
  `;
  
  education.forEach(item => {
    if (item.school || item.major) {
      html += `
        <div style="
          margin-bottom: ${style.education?.item?.marginBottom || 8}px;
          padding: ${style.education?.item?.padding || '8px 10px'};
          background-color: ${style.education?.item?.backgroundColor || '#ffffff'};
          border-radius: ${style.education?.item?.borderRadius || 4}px;
          border-left: 3px solid ${style.base?.primaryColor || '#333'};
        ">
          <div style="
            font-size: ${style.education?.itemMain?.fontSize || 13}px;
            font-weight: ${style.education?.itemMain?.fontWeight || 'bold'};
            color: ${style.education?.itemMain?.color || style.base?.primaryColor || '#333'};
          ">${item.school || '未填写学校'} - ${item.major || '未填写专业'}</div>
          <div style="
            font-size: ${style.education?.itemDate?.fontSize || 11}px;
            color: ${style.education?.itemDate?.color || style.base?.secondaryColor || '#666'};
            margin-top: 2px;
          ">${formatDate(item.startDate)} - ${item.endDate ? formatDate(item.endDate) : '至今'}</div>
        </div>
      `;
    }
  });
  
  html += '</div>';
  return html;
};

// 生成工作经验HTML (限制2个)
const generateWorkHTML = (limitedWork = null) => {
  const work = limitedWork || generateResumeContent().work.slice(0, 2);
  const template = resumeStore.currentTemplate;
  const style = template?.style || {};
  
  if (!work.length || work.every(item => !item.company && !item.position)) {
    return '';
  }
  
  let html = `
    <div style="margin-bottom: 15px;">
      <h2 style="
        font-size: ${style.work?.title?.fontSize || 16}px;
        font-weight: ${style.work?.title?.fontWeight || 'bold'};
        color: ${style.work?.title?.color || style.base?.primaryColor || '#333'};
        margin: 0 0 10px 0;
        padding-bottom: 3px;
        border-bottom: 2px solid ${style.work?.title?.borderBottom || style.base?.primaryColor || '#333'};
      ">工作经验</h2>
  `;
  
  work.forEach(item => {
    if (item.company || item.position) {
      html += `
        <div style="
          margin-bottom: ${style.work?.item?.marginBottom || 8}px;
          padding: ${style.work?.item?.padding || '8px 10px'};
          background-color: ${style.work?.item?.backgroundColor || '#ffffff'};
          border-radius: ${style.work?.item?.borderRadius || 4}px;
          border-left: 3px solid ${style.base?.primaryColor || '#333'};
        ">
          <div style="
            font-size: ${style.work?.itemHeader?.fontSize || 13}px;
            font-weight: ${style.work?.itemHeader?.fontWeight || 'bold'};
            color: ${style.work?.itemHeader?.color || style.base?.primaryColor || '#333'};
          ">${item.company || '未填写公司'} - ${item.position || '未填写职位'}</div>
          <div style="
            font-size: ${style.work?.itemDate?.fontSize || 11}px;
            color: ${style.work?.itemDate?.color || style.base?.secondaryColor || '#666'};
            margin: 2px 0 6px 0;
          ">${formatDate(item.startDate)} - ${item.endDate ? formatDate(item.endDate) : '至今'}</div>
          ${item.desc ? `
            <div style="
              font-size: ${style.work?.itemDesc?.fontSize || 12}px;
              line-height: ${style.work?.itemDesc?.lineHeight || 1.4};
              color: ${style.work?.itemDesc?.color || style.base?.secondaryColor || '#666'};
            ">${item.desc}</div>
          ` : ''}
        </div>
      `;
    }
  });
  
  html += '</div>';
  return html;
};

// 生成技能特长HTML (优化样式)
const generateSkillsHTML = () => {
  const skills = generateResumeContent().skills;
  const template = resumeStore.currentTemplate;
  const style = template?.style || {};
  
  if (!skills.length) {
    return '';
  }
  
  return `
    <div style="margin-bottom: 15px;">
      <h2 style="
        font-size: ${style.skills?.title?.fontSize || 16}px;
        font-weight: ${style.skills?.title?.fontWeight || 'bold'};
        color: ${style.skills?.title?.color || style.base?.primaryColor || '#333'};
        margin: 0 0 10px 0;
        padding-bottom: 3px;
        border-bottom: 2px solid ${style.skills?.title?.borderBottom || style.base?.primaryColor || '#333'};
      ">技能特长</h2>
      <div style="display: flex; flex-wrap: wrap; gap: 6px;">
        ${skills.map(skill => `
          <span style="
            padding: ${style.skills?.tag?.padding || '4px 8px'};
            background-color: ${style.skills?.tag?.bgColor || '#f0f0f0'};
            color: ${style.skills?.tag?.color || style.base?.primaryColor || '#333'};
            border-radius: ${style.skills?.tag?.borderRadius || 10}px;
            font-size: ${style.skills?.tag?.fontSize || 11}px;
            border: ${style.skills?.tag?.border || 'none'};
          ">${skill}</span>
        `).join('')}
      </div>
    </div>
  `;
};


// 生成空页面HTML
const generateEmptyPageHTML = () => {
  return `
    <div style="
      font-family: Microsoft YaHei, sans-serif;
      color: #333;
      padding: 20px;
      height: 100%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
    ">
      <div>
        <h2 style="color: #999; margin: 0;">简历内容为空</h2>
        <p style="color: #ccc; margin: 10px 0 0 0;">请先填写简历信息</p>
      </div>
    </div>
  `;
};

// 检查内容是否超出一页
const checkContentLength = () => {
  const resumeContent = generateResumeContent();
  let totalItems = 0;
  
  // 计算教育经历数量
  const educationCount = resumeContent.education.filter(item => item.school || item.major).length;
  totalItems += Math.min(educationCount, 3);
  
  // 计算工作经验数量
  const workCount = resumeContent.work.filter(item => item.company || item.position).length;
  totalItems += Math.min(workCount, 2);
  
  // 计算技能数量
  const skillsCount = resumeContent.skills.length;
  totalItems += Math.ceil(skillsCount / 8); // 假设每行8个技能
  
  // 基本信息总是占用1个位置
  totalItems += 1;
  
  return {
    totalItems,
    educationCount,
    workCount,
    skillsCount,
    isOverLimit: totalItems > 6 // 假设超过6个项目可能超页
  };
};

// 生成单页PDF内容
const generateSinglePageContent = () => {
  const resumeContent = generateResumeContent();
  let content = '';
  
  // Basic Info
  if (resumeContent.basic.name || resumeContent.basic.phone || resumeContent.basic.email) {
    content += generateBasicHTML();
  }
  
  // Education (限制3个)
  const limitedEducation = resumeContent.education.slice(0, 3);
  if (limitedEducation.length > 0) {
    content += generateEducationHTML(limitedEducation);
  }

  // Work Experience (限制2个)
  const limitedWork = resumeContent.work.slice(0, 2);
  if (limitedWork.length > 0) {
    content += generateWorkHTML(limitedWork);
  }

  // Skills
  if (resumeContent.skills.length > 0) {
    content += generateSkillsHTML();
  }
  
  return content || generateEmptyPageHTML();
};

// 日期格式化
const formatDate = (date) => {
  if (!date) return '未填写';
  const d = new Date(date);
  return `${d.getFullYear()}.${(d.getMonth() + 1).toString().padStart(2, '0')}`;
};

// 下载PDF (单页版本)
const downloadPDF = async () => {
  try {
    console.log('开始生成单页PDF');
    
    const pdf = new jsPDF('p', 'mm', 'a4');
    
    // 创建临时容器用于渲染
    const tempContainer = document.createElement('div');
    tempContainer.style.position = 'absolute';
    tempContainer.style.left = '-9999px';
    tempContainer.style.width = '210mm';
    tempContainer.style.height = '297mm';
    document.body.appendChild(tempContainer);
    
    // 创建单页元素
    const pageElement = document.createElement('div');
    pageElement.style.width = '210mm';
    pageElement.style.height = '297mm';
    pageElement.style.padding = '15mm';
    pageElement.style.boxSizing = 'border-box';
    pageElement.style.backgroundColor = '#ffffff';
    pageElement.style.fontFamily = 'Microsoft YaHei, sans-serif';
    pageElement.style.fontSize = '12px';
    pageElement.style.lineHeight = '1.4';
    pageElement.innerHTML = generateSinglePageContent();
    
    tempContainer.appendChild(pageElement);
    
    const canvas = await html2canvas(pageElement, {
      scale: 2,
      useCORS: true,
      allowTaint: true,
      logging: true
    });
    
    const imgData = canvas.toDataURL('image/png');
    pdf.addImage(imgData, 'PNG', 0, 0, 210, 297);
    
    document.body.removeChild(tempContainer);
    pdf.save('简历.pdf');
    console.log('PDF下载成功');
  } catch (error) {
    console.error('PDF生成失败:', error);
    alert('PDF生成失败，请检查控制台错误信息');
  }
};

// 打印PDF
const printPDF = () => {
  window.print();
};
</script>
